package v1

import (
	"net/http"
	"server/internal/model"
	"server/pkg/app"
	"strconv"

	"github.com/gin-gonic/gin"
)

func ArticleList(c *gin.Context) {
	ar := &model.Article{}
	pages := &app.Page{}
	pages.Info(c)
	ar_list, total := ar.List(pages)
	c.JSON(http.StatusOK, gin.H{
		"data":  ar_list,
		"total": total,
	})
}

func ArticleInfo(c *gin.Context) {
	article := &model.Article{}
	id := c.Param("id")
	article.ID, _ = strconv.Atoi(id)
	content := article
	c.JSON(http.StatusOK, content)
}

func CreateArticle(c *gin.Context) {
	article := &model.Article{}
	_ = c.ShouldBind(article)
	article.OwnerID = SetUserInfo(c)
	err := article.Create()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}

	c.String(http.StatusOK, "创建文章成功")
}

func UpdateArticle(c *gin.Context) {
	article := &model.Article{}
	_ = c.ShouldBind(article)
	err := article.Update()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": "修改文章失败",
		})
	}

	c.String(http.StatusOK, "user")
}

func DeleteArticle(c *gin.Context) {
	article := &model.Article{}
	_ = c.ShouldBind(article)
	article.Info()
	userinfo := GetUser(c)
	if article.Owner.Name != userinfo.Name {
		c.JSON(http.StatusOK, gin.H{
			"msg": "无权限",
		})
		go CreateLog(c, "文章", "删除文章"+article.Name+"失败："+"无权限")
		return
	}

	err := article.Delete()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": "创建文章失败",
		})
		go CreateLog(c, "文章", "删除文章"+article.Name+"失败："+err.Error())
		return
	}

	c.String(http.StatusOK, "删除文章成功")
	go CreateLog(c, "文章", "删除文章："+article.Name)
}
